using System;
using Microsoft.SharePoint;

namespace BilSimser.SharePoint.Common.Data
{
	/// <summary>
	/// Summary description for SharePointProvider.
	/// </summary>
	public class SharePointProvider
	{
		private SPSite site;
		private SPWeb web;

		/// <summary>
		/// Initializes a new instance of the <see cref="SharePointProvider"/> class.
		/// </summary>
		public SharePointProvider() : this("http://localhost")
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="SharePointProvider"/> class.
		/// </summary>
		/// <param name="url">The URL.</param>
		public SharePointProvider(string url)
		{
			site = new SPSite(url);
			try
			{
				Console.WriteLine(string.Format("Site ID is {0}", site.ID));
				site.AllowUnsafeUpdates = true;
				web = site.OpenWeb();
				web.AllowUnsafeUpdates = true;
			}
			catch (SPException ex)
			{
				Console.WriteLine(ex.ToString());
				throw new ApplicationException(string.Format("Invalid url {0} for portal.", url));
			}
		}

		/// <summary>
		/// Gets a value indicating whether this instance is valid site.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is valid site; otherwise, <c>false</c>.
		/// </value>
		public bool IsValidSite
		{
			get { return site.ID != Guid.Empty; }
		}

		/// <summary>
		/// Creates the list.
		/// </summary>
		/// <param name="listName">Name of the list.</param>
		/// <returns></returns>
		public Guid CreateList(string listName)
		{
			SharePointListProvider listProvider = new SharePointListProvider(web);
			return listProvider.CreateList(listName);
		}

		/// <summary>
		/// Deletes the list.
		/// </summary>
		/// <param name="guid">The GUID.</param>
		/// <returns></returns>
		public bool DeleteList(Guid guid)
		{
			SharePointListProvider listProvider = new SharePointListProvider(web);
			return listProvider.DeleteList(guid);
		}

		/// <summary>
		/// Gets the name of the list by.
		/// </summary>
		/// <param name="listName">Name of the list.</param>
		/// <returns></returns>
		public Guid GetListByName(string listName)
		{
			SharePointListProvider listProvider = new SharePointListProvider(web);
			return listProvider.GetListByName(listName);
		}

		/// <summary>
		/// Gets the list by id.
		/// </summary>
		/// <param name="guid">The GUID.</param>
		/// <returns></returns>
		public SharePointListDescriptor GetListById(Guid guid)
		{
			SharePointListProvider listProvider = new SharePointListProvider(web);
			return listProvider.GetListById(guid);
		}
	}
}
